package com.nx.platform.es.biz.esspider.handler;

import com.google.common.base.Preconditions;
import com.nx.platform.es.biz.esspider.resource.DBManager;
import com.nx.platform.es.common.utils.MoreMaps;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Constructor;
import java.util.Map;

/**
 * 过滤处理器工厂
 *
 * @author
 * @since 2017年3月24日
 */
public class HandlerFactory implements Constants {

    /**
     * 创建过滤处理器
     *
     * @param settings handle settings
     * @return
     * @throws Exception
     */
    @NotNull
    public static Handler createFilter(DBManager dbManager, Map<?, ?> settings) throws Exception {
        //
        String simpleClassName = MoreMaps.getString(settings, HANDLERS_CLASS_NAME);
        String className = Handler.class.getPackage().getName() + "." + simpleClassName;
        Class<?> clazz = Class.forName(className);
        //
        HandlerDefine define = clazz.getAnnotation(HandlerDefine.class);
        String defineErrorMsg = "handle type not found, class: " + className;
        Preconditions.checkNotNull(define, defineErrorMsg);
        //
        HandlerType type = define.value();
        String typeErrorMsg = "handle type is null, class: " + className;
        Preconditions.checkNotNull(type, typeErrorMsg);
        //
        switch (type) {
            case SIMPLE:
                Constructor<?> sc = clazz.getConstructor();
                String scErrorMsg = "handle constructor() not found, class: " + className;
                Preconditions.checkNotNull(sc, scErrorMsg);
                Handler simpleHandler = (Handler) sc.newInstance();
                simpleHandler.init(settings);
                return simpleHandler;
            case DB:
                Constructor<?> dc = clazz.getConstructor(String.class, DBManager.class);
                String dcErrorMsg = "handle constructor(String.class, DBManager.class) not found, class: " + className;
                Preconditions.checkNotNull(dc, dcErrorMsg);
                String id = MoreMaps.getString(settings, HANDLERS_ID);
                Handler dbHandler = (Handler) dc.newInstance(id, dbManager);
                dbHandler.init(settings);
                return dbHandler;
        }
        //
        String errorMsg = "handle type no support, class: " + className;
        throw new IllegalArgumentException(errorMsg);
    }

}
